// pages/order/orderlist/orderlist.js
const App = getApp()
let timeTranfer = require('../../../utils/util.js').timeTranfer
let AJAX = require('../../../utils/util.js').AJAX
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    activeNum: 1,
    orderList: [],
    total: 0,
    pageSize: 10,
    pageNum: 1,
    navH: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      activeNum: options.type || '1',
      navH: App.globalData.navHeight
    })
    this.requestList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /** 
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let vm = this
    if (this.data.total > this.data.orderList.length) {
      this.setData({
        pageNum: vm.data.pageNum + 1
      })
      this.requestList(true)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  tabActive(e) {
    let _type = e.currentTarget.dataset.type
    this.setData({
      activeNum: _type
    })
    this.requestList()
  },
  navBack() {
    wx.switchTab({
      url: '/pages/mine/mine',
    })
  },
  toInfo(e) {
    let _sn = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/order/orderinfo/orderinfo?sn=' + _sn,
    })
  },
  toCancle(e){
    let vm =this
    let _sn = e.currentTarget.dataset.id
    AJAX("order/cancel","POST",{
      order_sn:_sn
    }).then(res=>{
      vm.requestList()
    })
  },
  topay(e) {
    let _sn = e.currentTarget.dataset.id
    // pay/enter/编号-支付类型-类型 ?code=值
    let vm = this
    // 登录
    wx.login({
      success: e => {
        let _path = 'pay/enter/' + _sn + '-order?code=' + e.code
        AJAX(_path, 'get', {}).then(res => {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success(res) {
              vm.requestList()
            },
            fail(res) {}
          })
        })
      }
    })



  },
  requestList(str) {
    let vm = this
    let AJAX = require('../../../utils/util.js').AJAX
    AJAX('order/list', 'get', {
      order_status: vm.data.activeNum,
      page: vm.data.pageNum
    }).then(res => {
      let _data = []
      if (str) {
        _data = vm.data.orderList
      }
      if (res.data) {
        res.data.forEach(function(item) {
          item.create_time = timeTranfer(item.create_time)
          _data.push(item)
        })
      }
      this.setData({
        orderList: _data,
        total: res.header["X-Pagination-Total-Count"]
      })
    })
  }
})